package utils;

import java.nio.ByteBuffer;

public class HexUtils {
    public static String toHex(int dec,int len){

        int sub = 0xffffffff;
        switch (len){
            case 1:
                sub = 0xFF;
                break;
            case 2:
                sub = 0xffff;
                break;
            case 3:
                sub = 0xffffff;
                break;
        }

        String hex = Integer.toHexString(dec & sub);
        if (hex.length()%2 == 1){
            hex = "0"+hex;
        }

        return StringUtils.chunkedByEmpty(hex,2);
    }

    /**
     * @param str 如：24 24 c6 89 28 00 0e 03 01 04 14 d9 40 00 ce 6c 23 00 00 63 0a
     * @return byte{0x24,0x24,0xc6}
     */
    public static byte[] toHexBytes(String str) throws Exception{
        String[] list = str.split(" ");
        ByteBuffer bytes = ByteBuffer.allocate(list.length);
        for (String s:list){
            if (s.trim().isEmpty()){
                continue;
            }else{
                if (s.length()!= 2){
                    throw new Exception("数据异常，字符串中间可能缺少空格："+s);
                }
            }

            bytes.put((byte) (Integer.parseInt(s.trim(),16)&0xFF));
        }

        return bytes.array();
    }

    public static String toHexStr(byte[] data){
        StringBuilder builder = new StringBuilder();
        for (byte b:data){
            String hex = Integer.toHexString(b&0xFF);
            if (hex.length() == 1){
                builder.append("0");
            }

            builder.append(hex);
            builder.append(" ");
        }

        return builder.toString();
    }

    public static String toHexStr(byte[] data,int offset,int len){
        StringBuilder builder = new StringBuilder();
        for (int i = offset; i < offset+len; i++) {
            byte b = data[i];
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                builder.append("0");
            }

            builder.append(hex);
            builder.append(" ");
        }

        return builder.toString();
    }

    public static int toInt(byte[] data,int offset,int len){

        if (len > 4){
            //int类型最多占4个字节
            return -1;
        }

        int num = 0;
        for (int i= 0;i<len;i++){
            num = num << 8;
            num = num |(data[i+offset] &0xFF);
        }
        return num;
    }

    /**
     * 数字转为二进制字符串
     * 如输入2，返回 00000000000000000000000000000010
     * @param num
     */
    public static String convertToBinary(int num,int len) {
        String binaryString = Integer.toBinaryString(num);
        return String.format("%"+(len*8)+"s", binaryString).replace(' ', '0');
    }
}
